/*

//创建投射光线对象
const raycaster = new THREE.Raycaster()

//鼠标的位置对象
const mouse = new THREE.Vector2()

//监听鼠标的位置

*/


import *  as THREE from 'three'
import { AxesHelper } from 'three';
import gsap from 'gsap'
import * as dat from 'dat.gui'
const gui = new dat.GUI()
//导入轨道控制器
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'

//1.创建场景
const scene = new THREE.Scene()

//2.创建相机 (透视相机)
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

//设置相机位置
camera.position.set(0, 0, 15);
scene.add(camera);







const cubeGeometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({
  wireframe: true
})
const redMaterial = new THREE.MeshBasicMaterial({
  color: "#ff0000"
})
let cubeArr = []
//1000个立方体
for(let i = -5; i<5; i++){
  for(let j= -5; j<5; j++){
    for(let z = -5; z < 5; z ++){
      const cube = new THREE.Mesh(cubeGeometry, material)
      cube.position.set(i, j ,z)
      scene.add(cube)
      cubeArr.push(cube)
    }
  }
}

//创建投射光线对象
const raycaster = new THREE.Raycaster()

//鼠标的位置对象
const mouse = new THREE.Vector2()


//监听鼠标的位置
window.addEventListener('mousemove', (event)=>{
  mouse.x = (event.clientX / window.innerWidth) * 2 -1

  // 因为three和实际鼠标的y轴是反的，所以加-号
  mouse.y = -(event.clientY / window.innerWidth) * 2 -1

  //设置射线的起点和方向
  raycaster.setFromCamera(mouse, camera)

  //检查设置和提供的数组中那些对象进行了相交
  let result = raycaster.intersectObjects(cubeArr)
  // result[0].object.material = redMaterial
  result.forEach(item=>{
    item.object.material = redMaterial
    console.log(item)
  })
})






//初始化渲染器
const renderer = new THREE.WebGLRenderer();
//设置渲染器大小
renderer.setSize(window.innerWidth, window.innerHeight);

//将webgl渲染的canvas内容添加到body
document.body.appendChild(renderer.domElement)

//使用渲染器，通过相机将场景渲染进来
renderer.shadowMap.enabled = true
renderer.render(scene, camera);

//添加坐标辅助器
const axesHelper = new AxesHelper(5)
scene.add(axesHelper)
//创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;

const clock=new THREE.Clock()

function render(){
  //获取时钟运行的总时长
  let time = clock.getElapsedTime();

  controls.update()
  renderer.render(scene,camera)
  //调用下一帧的时候就会调用render渲染
  requestAnimationFrame(render)
}

render();